<template>
    <div class="toc-container">
        <h2 class="title">首页</h2>

        <RightLists :list="newData" :handleClick="props.handleClick" />

    </div>
</template>

<script setup>
import debounce from "@/utils/debounce.js";
import { defineProps, onMounted, computed, ref } from "vue";
import RightLists from './RightLists.vue';
const props = defineProps({
    list: {
        type: Array,
        default: []
    },
    handleClick: {
        type: Function
    },
    handleScroll: {
        type: Function,
    }
});


const ChosenAnchor = ref("");

const newData = computed(() => {
    const newToc = (data = []) => {
        return data.map((t) => {
            //迭代循环
            return {
                name: t.name,
                anchor: t.anchor,
                isSelect: ChosenAnchor.value === t.anchor,
                children: newToc(t.children),
            }
        })
    }
    return newToc(props.list);
})

const doms = computed(() => {
    const doms = [];
    const containDoms = (toc) => {
        for (const item of toc) {
            if (item.children && item.children.length > 0) {
                //判断有没有子元素如果有就继续将子元素放给他
                containDoms(item.children);
            }
            doms.push(document.getElementById(item.anchor)); //将其元素给doms的数组中去
        }
    }
    containDoms(props.list);
    return doms;
})



function setSelect() {
    const range = 200; //范围
    const unrange = -5; //其误差
    ChosenAnchor.value = "";
    for (const dom of doms.value) {
        if (!dom) {
            return;
        }
        const domTop = dom.getBoundingClientRect().top; //获取到其top为多少，dom的元素为那些h元素
        if (domTop >= unrange && domTop < range) {
            //判断是否在误差以及范围之内
            ChosenAnchor.value = dom.id;
            return;
        } else if (domTop > range) {
            //如果domTop>range就不处理
            return;
        } else {
            //如果在上面就赋予他值
            ChosenAnchor.value = dom.id;
        }
    }
}

onMounted(() => {
    const newScroll = debounce(setSelect, 10);
    props.handleScroll(newScroll);
})

</script>

<style lang="less" scoped>
@import url("@/style/var.less");

.toc-container {
    width: 100%;
    height: 100%;
}

.title {
    font-weight: bold;
    margin: 20px 0;
    font-size: 33px;
    color: @words;
}
</style>